package initConfig

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/rs/zerolog/log"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"os"
	"path/filepath"
	"sync"
	"time"
	"webGoDemo/conf"
)

var once sync.Once

var GlobalDB *gorm.DB

func DBInit() {

	//1 读取数据放到conf中
	filePath, _ := getConfigFile()
	config, _ := Load(filePath)
	//2 将conf 中的数据初始化
	// 3 连接数据库
	ConnectDB(config)
}
func getConfigFile() (string, error) {
	defaultConfigFile, err := os.Getwd()
	if err != nil {
		return "", err
	}
	var configFileName string
	pflag.StringVar(&configFileName,
		"conf",
		filepath.Join(defaultConfigFile, "/conf/application.yaml"),
		"explicitly defines the path, name and extension of the config file")
	pflag.Parse()
	return configFileName, nil
}

func Load(fileName string) (*conf.Conf, error) {
	// from file
	viper.SetConfigFile(fileName)
	err := viper.ReadInConfig()
	if err != nil {
		log.Warn().Err(err).Msg("viper read in config failed, use env or default")
		return nil, err
	}
	//logs.Info().Interface("setting", viper.AllSettings()).Msg("all viper setting")
	// unmarshal
	config := new(conf.Conf)
	err = viper.Unmarshal(&config)
	if err != nil {
		return nil, err
	}
	//logs.Info().Interface("config", config).Msg("config before parse")

	return config, nil
}

func ConnectDB(config *conf.Conf) {

	once.Do(func() {
		//gorm
		mysqlArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
			config.Mysql.User, config.Mysql.Password, config.Mysql.Host, config.Mysql.Port, config.Mysql.Database)
		db, err := gorm.Open("mysql", mysqlArgs)
		if err != nil {
			panic("gorm open mysql failed")
			return
		}
		sqlDB := db.DB()
		sqlDB.SetMaxIdleConns(10)  //空闲连接数
		sqlDB.SetMaxOpenConns(100) //最大连接数
		sqlDB.SetConnMaxLifetime(time.Minute)
		db.LogMode(true)
		GlobalDB = db
	})

}
